package com.shchuangzhi.smartguard.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceCategory;
import android.preference.PreferenceFragment;
import android.preference.PreferenceScreen;
import android.preference.SwitchPreference;
import android.support.annotation.Nullable;
import android.widget.Toast;

import com.elvishew.xlog.XLog;
import com.shchuangzhi.smartguard.ActivityManager;
import com.shchuangzhi.smartguard.LoginActivity;
import com.shchuangzhi.smartguard.R;
import com.shchuangzhi.smartguard.core.Consts;
import com.shchuangzhi.smartguard.core.DBHelper;
import com.shchuangzhi.smartguard.core.Machine;
import com.shchuangzhi.smartguard.core.Mode;
import com.shchuangzhi.smartguard.core.NotifyMessage;
import com.shchuangzhi.smartguard.core.NotifyPrinter;
import com.shchuangzhi.smartguard.core.User;
import com.shchuangzhi.smartguard.core.Util;

/**
 * Created by j_hu on 5/4/17.
 */

public class Settings extends PreferenceFragment implements FragmentNamed {

    private DBHelper dbHelper;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getPreferenceManager().setSharedPreferencesName(Consts.APP_FULL_NAME);
        addPreferencesFromResource(R.xml.settings);

        dbHelper = new DBHelper(this.getActivity());

        final SharedPreferences sp = getPreferenceManager().getSharedPreferences();
        String hostPref = sp.getString(getString(R.string.host_preference), "http://");
        String networkPref = sp.getString(getString(R.string.network_preference), "http://www.baidu.com");
        String terminalNamePref = sp.getString(getString(R.string.terminal_name_preference), Util.getHardwareAddr());

        EditTextPreference edit = (EditTextPreference)findPreference(getString(R.string.host_preference));
        edit.setText(hostPref);
        edit = (EditTextPreference)findPreference(getString(R.string.network_preference));
        edit.setText(networkPref);
        edit = (EditTextPreference)findPreference(getString(R.string.terminal_name_preference));
        edit.setText(terminalNamePref);
        edit.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                boolean validateOk = false;
                String val = (String)newValue;
                if (val != null && !val.equals("")) {
                    String[] split = val.split("-");
                    if (split.length >= 3) {
                        try {
                            Integer.parseInt(split[2]);
                            validateOk = true;
                        } catch(Exception e) {
                            XLog.e("", e);
                        }
                    }
                }
                if (!validateOk) {
                    Toast.makeText(getActivity(), Consts.INVALID_TERMINAL_NAME, Toast.LENGTH_LONG).show();
                }
                return validateOk;
            }
        });

        SwitchPreference autoSwitch = (SwitchPreference)findPreference(getString(R.string.auto_switch_preference));
        SwitchPreference inOrOut = (SwitchPreference)findPreference(getString(R.string.mode_preference));
        SwitchPreference machineType = (SwitchPreference)findPreference(getString(R.string.machine_mode_preference));

        inOrOut.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                Mode.getInstance().reset();

                boolean isChecked = (Boolean)newValue;
                if (isChecked) {
                    Mode.getInstance().in();
                } else {
                    Mode.getInstance().out();
                }

                NotifyPrinter.getInstance().notify(
                        NotifyMessage.wrap("",
                                Consts.NOTIFY_STATE_BUTTON_SWITCH_MODE,
                                Consts.NOTIFY_INOUT_LIST_SWITCH_MODE,
                                Consts.NOTIFY_MAIN_OP_SWITCH_MODE,
                                Consts.NOTIFY_SCHOOL_CHANGED));

                SwitchPreference autoSwitch = (SwitchPreference)findPreference(getString(R.string.auto_switch_preference));
                autoSwitch.setChecked(false);

                return true;
            }
        });

        PreferenceScreen preferenceScreen = (PreferenceScreen) findPreference(getString(R.string.preferenceScreen));
        PreferenceCategory systemPrefCategory = (PreferenceCategory) findPreference(getString(R.string.system_settings_pref_category));
        PreferenceCategory functionPrefCategory = (PreferenceCategory)findPreference(getString(R.string.function_settings_pref_category));
        PreferenceCategory userPrefCategory = (PreferenceCategory)findPreference(getString(R.string.user_settings_pref_category));

        User user = User.get();
        if (user != null) {
            if (!User.get().isAdmin()) {
                preferenceScreen.removePreference(systemPrefCategory);
                preferenceScreen.removePreference(functionPrefCategory);
                if (Machine.getInstance().getType() != Machine.MachineType.Gate) {
                    preferenceScreen.removePreference(userPrefCategory);
                }
            }
        } else {
            Activity activity = ActivityManager.getInstance().getCurrentActivity();
            if (activity != null) {
                Intent intent = new Intent(activity, LoginActivity.class);
                activity.startActivity(intent);
                activity.finish();
            }
        }
    }

    @Override
    public String Name() {
        return Consts.SETTINGS_FRAGMENT_NAME;
    }

    @Override
    public Fragment Fragment() {
        return this;
    }
}
